package drds.data_propagate.parse.table_meta_data;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.ConcurrentMap;

@Slf4j
public class TableMetaDataClassPathXmlApplicationContextManager {
    private static ConcurrentMap<String, ClassPathXmlApplicationContext> destinationToClassPathXmlApplicationContextMap = Maps.newConcurrentMap();

    /**
     * 不同的destination建立不同的ClassPathXmlApplicationContext
     */
    public static TableMetaDataStore build(String destination, String beansXmlPath) {
        if (StringUtils.isNotEmpty(beansXmlPath)) {
            ClassPathXmlApplicationContext classPathXmlApplicationContext = destinationToClassPathXmlApplicationContextMap.get(destination);
            if (classPathXmlApplicationContext == null) {
                synchronized (destinationToClassPathXmlApplicationContextMap) {
                    if (classPathXmlApplicationContext == null) {
                        classPathXmlApplicationContext = new ClassPathXmlApplicationContext(beansXmlPath);
                        destinationToClassPathXmlApplicationContextMap.put(destination, classPathXmlApplicationContext);
                    }
                }
            }
            TableMetaDataStore tableMetaDataStore = (TableMetaDataStore) classPathXmlApplicationContext.getBean("tableMetaDataStore");
            log.info("{} init ClassPathXmlApplicationContext with {}", destination, beansXmlPath);
            return tableMetaDataStore;
        } else {
            return null;
        }
    }

    public static void destory(String destination) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = destinationToClassPathXmlApplicationContextMap.remove(destination);
        if (classPathXmlApplicationContext != null) {
            log.info("{} destory classPathXmlApplicationContext", destination);
            classPathXmlApplicationContext.close();
        }
    }
}
